import { _decorator, Component, Label, Node } from 'cc';
import { DataHelper } from '../system/DataHelper';
import { AppControll, EventName, PopView, secretShop_config } from '../manager/AppControll';
import { SecretShopItem } from './SecretShopItem';
import { GameData } from '../system/GameData';
import EvtManger from '../tools/EvtManger';
import { PopManager } from '../manager/PopManager';
import { SystemMessage } from './SystemMessage';
import { SoundManager } from '../manager/SoundManger';
const { ccclass, property } = _decorator;

@ccclass('SecretShop')
export class SecretShop extends Component {
    @property(Node)
    mItemLt: [Node] = [null];
    @property(Label)
    mLbTotalTimes: Label = null;
    mIsLock: boolean;

    protected onLoad(): void {
        GameData.isPause = true;
        this.InitSecretShop();
        this.RegisterEvents();
        this.ShowGoods();
    }

    RegisterEvents() {
        EvtManger.on(EventName.updateShop, this, this.InitSecretShop)
    }

    protected onDestroy(): void {
        EvtManger.off(EventName.updateShop, this, this.InitSecretShop)
    }

    InitSecretShop() {
        this.mLbTotalTimes.string = GameData.playerData.secretShopFreeTimes + GameData.playerData.secretShopVideoTimes + "";
        let have = false
        this.mItemLt.forEach(nd => { if (nd.active) have = true; })
        if (!have) {
            GameData.playerData.secretShopReward = GameData.GetGoods();
            GameData.SavePlayData();
            this.ShowGoods();
        }
    }

    ShowGoods() {
        let count = 0;
        let lt = [];
        GameData.playerData.secretShopReward.forEach(id => {
            let config = DataHelper.GetSecretShopConfigById(id);
            lt.push(config);
        })
        this.mItemLt.forEach(node => node.active = false);
        lt.forEach(element => {
            this.mItemLt[count].active = true;
            this.mItemLt[count].getComponent(SecretShopItem).InitItem(element);
            count++;
        });
    }

    OnChangeGoods() {
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        if (this.mIsLock) return;
        this.mIsLock = true;
        this.scheduleOnce(() => {
            this.mIsLock = false;
        }, 0.5)
        AppControll.Platform.ShowRewardVideoAd(this, (bool, str) => {
            this.mIsLock = false;
            if (!bool) {
                PopManager.Instance<PopManager>().ShowPop(PopView.systemMessage, (node) => {
                    node.getComponent(SystemMessage).InitContent(str);
                })
                return;
            }
            GameData.playerData.secretShopReward = GameData.GetGoods();
            this.InitSecretShop();
            GameData.SavePlayData();
            this.ShowGoods();
        })

    }

    OnClose() {
        SoundManager.Instance<SoundManager>().PlayEffect(GameData.btnClick);
        GameData.isPause = false;
        this.node.destroy();
    }
}


